#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@File: CrsReportCase.py
@Author: lijk34925 
@Date: 2024/12/12 19:52
@desc: 请补充本模块功能说明
"""
import json

from AmlScripts.amlConfig import amlConfig
from BladeFerm.ApiModule.httpRequest import HttpRequest
from BladeFerm.databases import DB_APP
from BladeFerm.databases.DealSql.MakeSql import MakeSql
from BladeFerm.utils.OperationExcel import OperationExcel
from BladeFerm.Lib.Common import logger


class CrsReportCase:
    def __init__(self, casePath, env_name='mysql_auto'):
        self.case_path = casePath
        self.sheets = dict()
        system_odbc_config = amlConfig.get(env_name).get('databases')
        DB_APP.make_db(**system_odbc_config)
        self.http = HttpRequest()
        self.jinJia = MakeSql()
        self.read_case_modul()

    # step1: 读取用例模板
    def read_case_modul(self):
        self.sheets['模板'] = OperationExcel('', '模板', self.case_path).readExcelDatas()
        self.sheets['用例'] = OperationExcel('', '用例', self.case_path).readExcelDatas()

    # step2: 读取CRS的纳税人识别号校验规则描述信息
    @staticmethod
    def read_crs_rule(client_type, country):
        sql_dict = (f"select t.sub_entry as company_id, t.dict_prompt as company_name from hspbs.pbs_dictionary t "
                    f"where t.dict_entry = 'B0093' and t.dict_prompt like '%{country}%'")
        sql_responses = DB_APP.run_one_sql(sql_dict)
        params = dict()
        if sql_responses:
            tp_company_id = sql_responses[0].get('COMPANY_ID')
            tp_company_name = sql_responses[0].get('COMPANY_NAME')
            sql_rule = (f"select taxpayer_id_no_country as company_id, '{tp_company_name}' as tp_company_name, sql_text, memo as description from hsamlcrs.amlcrs_crs_taxpayerid_check "
                        f"where taxpayer_id_no_country = '{tp_company_id}' and client_type = {client_type}")
            sql_responses2 = DB_APP.run_one_sql(sql_rule)
            params = sql_responses2[0]
        test_point = f"生成[{country}]国家的CRS纳税人识别号，要求编号为[{params}]"
        logger.info(test_point)
        return params

    # step3: ai生成纳税人识别参数
    def get_params_by_ai(self, testPoint: str, crsParams: dict):
        params = {"id": 6, "params": json.dumps({"TestPoint": testPoint, "CrsRule": crsParams})}
        logger.info(f"ai params : {params}")
        url_ai = 'http://127.0.0.1:8088/fast-generator-data/gen/prompt/run'
        response = self.http.doPost(url=url_ai, data=json.dumps(params), headers={'Content-Type': 'application/json;charset=UTF-8;'})
        result = dict()
        if response and response.json().get('code') == 0:
            result = response.json().get('data')
        logger.info(f"ai result : {result}")
        return result

    # step4: 根据AI生成的测试数据填充用例步骤
    def updateCaseStep(self, case_params: dict, case_step: dict) -> list:
        cast_steps = list()
        case_step_1 = case_step.copy()
        rightFlag = True if case_params.get('case_flag') == '正' else False
        modules = self.sheets['模板']
        test_data = self.jinJia.sql_update_field(modules[0].get('输入数据'), case_params)
        case_step_1.update({'正反例': case_params.get('case_flag'), '操作步骤': modules[0].get('操作步骤'), '输入数据': test_data, '预期结果': modules[0].get('预期结果')})
        cast_steps.append(case_step_1)
        case_step_2 = {'操作步骤': modules[1].get('操作步骤'), '输入数据': modules[1].get('输入数据'), '预期结果': modules[1].get('预期结果')}
        cast_steps.append(case_step_2)
        if rightFlag:
            case_step_3 = {'操作步骤': modules[2].get('操作步骤'), '输入数据': modules[2].get('输入数据'), '预期结果': modules[2].get('预期结果')}
        else:
            case_step_3 = {'操作步骤': modules[5].get('操作步骤'), '输入数据': modules[5].get('输入数据'), '预期结果': modules[5].get('预期结果')}
        cast_steps.append(case_step_3)
        logger.info(f"case step: {cast_steps}")
        return cast_steps

    # step5: 生成的用例上传到blade平台
    def push_case(self, case_steps: list):
        blade_case_upload = 'http://127.0.0.1:8015/case/uploadCase/'
        params = {'username': 'lijk34925', 'cases': case_steps}
        self.http.doPost(url=blade_case_upload, data=json.dumps(params),
                         headers={'Content-Type': 'application/json;charset=UTF-8;'})

    """
    创建用例的主流程逻辑，步骤见上
    """
    def make_case(self):
        case_steps_list = list()
        for data in self.sheets['用例']:
            logger.info(f"case row: {data}")
            case_point = data.get('测试点')
            casePath = data.get('用例路径')
            case_path_list = casePath.split('/')
            client_type = 0 if case_path_list[-2] == '个人' else 1
            country = case_path_list[-1]
            dataParams = self.read_crs_rule(client_type, country)
            case_params = self.get_params_by_ai(case_point, dataParams)
            steps = self.updateCaseStep(case_params, data)
            self.push_case(steps)     # 推送用例
            # case_steps_list.extend(steps)
        # OperationExcel('', '用例', self.case_path).write_data(case_steps_list, "_CRS纳税人校验用例")


if __name__ == '__main__':
    case_path = "E:\AutoTest\Project\金融反洗钱项目\web应用\数据预埋\基础功能\CRS管理\CRS规则校验\CRS纳税人识别号校验用例1.xlsx"
    CRS = CrsReportCase(case_path)
    CRS.make_case()

